<template>
  <div id="Permit_vue">
    <div class="toolbar">
      <el-form inline @submit.native.prevent>
        <el-form-item>
          <el-input :placeholder="'请输入关键字 ( ' + tableParam.dropdown[tableParam.keycurrent].value + ' )'" v-model="tableParam._keyword" size="mini"></el-input>
        </el-form-item>
        <el-form-item>
          <el-dropdown split-button="" type="primary" @command="updateKeyCurrent" @click="tableParam.keyword = tableParam._keyword; tableParam.pageno = 1; query();" size="mini">
            <i class="el-icon-search" style="margin-right:5px;"></i>查询
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="item in tableParam.dropdown" :command="item.key" :key="item.key + '_dropdown'">{{item.value}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button type="primary" icon="el-icon-plus" @click="recordFormInit(); recordForm.visible = true; recordForm.flag = true;" size="mini">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-alert title="谨慎操作，尽量避免删除或修改正在使用的权限，防止不可逆情况的发生" type="warning" :show-icon="true" style="line-height:20px; padding-right:25px;"></el-alert>
        </el-form-item>
      </el-form>
    </div>
    <sample-table :data="records" :isloading="tableParam.loading" sortcustom @afterSortChange="sortChange" @selectionChange="selectionChange">
      <sample-table-header slot="header">
        <sample-table-header-selection />
        <sample-table-header-column label="主键" prop="ZK_ID" sortable />
        <sample-table-header-column label="路径" prop="ZK_PATH" sortable />
        <sample-table-header-column label="名称" prop="ZK_NAME" sortable />
        <sample-table-header-column label="组件" prop="ZK_COMPONENT" sortable />
        <sample-table-header-column label="状态" prop="ZK_ISHIDDEN" sortable />
        <sample-table-header-column label="图标" prop="ZK_ICON" sortable />
        <sample-table-header-column label="类型" prop="ZK_ISLEAF" sortable />
        <sample-table-header-column label="父级" prop="ZK_PARENT" sortable />
        <sample-table-header-column label="操作" />
      </sample-table-header>
      <sample-table-body slot-scope="scope" :row="scope.row" :index="scope.index" slot="body">
        <sample-table-body-selection />
        <sample-table-body-column prop="ZK_ID" />
        <sample-table-body-column prop="ZK_PATH" />
        <sample-table-body-column prop="ZK_NAME" />
        <sample-table-body-column prop="ZK_COMPONENT" />
        <sample-table-body-column>
          <span v-if="scope.row.ZK_ISHIDDEN === '0'" class="tag-primary">显示</span>
          <span v-if="scope.row.ZK_ISHIDDEN === '1'" class="tag-success">隐藏</span>
        </sample-table-body-column>
        <sample-table-body-column prop="ZK_ICON" />
        <sample-table-body-column prop="ZK_ISLEAF">
          <span v-if="scope.row.ZK_ISLEAF === '1'" class="tag-primary">叶子节点</span>
          <span v-if="scope.row.ZK_ISLEAF === '0'" class="tag-success">普通节点</span>
        </sample-table-body-column>
        <sample-table-body-column prop="ZK_PARENT" />
        <sample-table-body-column>
          <i class="el-icon-edit icon-btn-edit" @click="recordFormInit(); getRecord(scope)"></i>
          <i class="el-icon-delete icon-btn-del" @click="delRecord(scope)"></i>
        </sample-table-body-column>
      </sample-table-body>
    </sample-table>
    <el-col :span="24" class="botton_toolbar">
      <el-button type="danger" :disabled="selection.length === 0" icon="el-icon-delete" @click="batchDelete" size="mini">
        批量删除<span v-if="selection.length !== 0"> (共{{selection.length}}条)</span>
      </el-button>
      <el-pagination layout="prev, pager, next, jumper, total" :page-size="tableParam.pagesize" :current-page="tableParam.pageno" :total="tableParam.total" @current-change="currentChange" style="float:right;">
      </el-pagination>
    </el-col>
    <el-dialog :title="recordForm.flag ? '新增' : '编辑'" :visible.sync="recordForm.visible">
      <el-form ref="recordForm" class="recordForm" label-width="80px" :model="recordForm.record" :rules="recordformRules" @submit.native.prevent>
        <el-form-item label="主　键" prop="ZK_ID">
          <el-input v-model="recordForm.record.ZK_ID" placeholder="请输入主键" :disabled="!recordForm.flag"></el-input>
        </el-form-item>
        <el-form-item label="路　径" prop="ZK_PATH">
          <el-input v-model="recordForm.record.ZK_PATH" placeholder="请输入路径"></el-input>
        </el-form-item>
        <el-form-item label="名　称" prop="ZK_NAME">
          <el-input v-model="recordForm.record.ZK_NAME" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="组　件" prop="ZK_COMPONENT">
          <el-input v-model="recordForm.record.ZK_COMPONENT" placeholder="请输入组件（详情询问前台）"></el-input>
        </el-form-item>
        <el-form-item label="隐　藏">
          <el-switch v-model="recordForm.ishidden"></el-switch>
          <i :class="recordForm.record.ZK_ICON" style="padding-left:20px;"></i>
        </el-form-item>
        <el-form-item label="图　标">
          <el-input v-model="recordForm.record.ZK_ICON" placeholder="请输入图标"></el-input>
        </el-form-item>
        <el-form-item label="类　型">
          <el-radio class="radio" v-model="recordForm.record.ZK_ISLEAF" label="1">叶子节点</el-radio>
          <el-radio class="radio" v-model="recordForm.record.ZK_ISLEAF" label="0">普通节点</el-radio>
        </el-form-item>
        <el-form-item label="权　重" prop="ZK_SORT">
          <el-input-number v-model="recordForm.record.ZK_SORT" placeholder="请输入权重（数字越小等级越靠前）"></el-input-number>
        </el-form-item>
        <el-form-item label="父　级">
          <el-input v-model="recordForm.record.ZK_PARENT" placeholder="请输入父级主键"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="recordForm.visible = false;">取 消</el-button>
        <el-button type="primary" @click="recordForm.flag ? insertRecord() : updateRecord()">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selection: [],
      records: [],
      tableParam: {
        keyword: '',
        _keyword: '',
        prop: '',
        order: '',
        pagesize: 15,
        pageno: 1,
        total: 0,
        loading: false,
        dropdown: [
          { key: 'ZK_ID', value: '主键' },
          { key: 'ZK_PATH', value: '路径' },
          { key: 'ZK_COMPONENT', value: '组件' },
          { key: 'ZK_NAME', value: '名称' },
        ],
        keycurrent: 0,
      },
      recordForm: {
        flag: true,
        record: {
          ZK_ID: '',
          ZK_PATH: '',
          ZK_COMPONENT: '',
          ZK_NAME: '',
          ZK_ISHIDDEN: '',
          ZK_ICON: '',
          ZK_ISLEAF: '1',
          ZK_PARENT: '',
          ZK_SORT: '',
          EB_ISDELETE: '',
        },
        visible: false,
        ishidden: false,
        index: -1,
      },
      recordformRules: {
        ZK_ID: [{ required: true, message: '请输入主键', trigger: 'blur' }],
        ZK_PATH: [{ required: true, message: '请输入路径', trigger: 'blur' }],
        ZK_NAME: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        ZK_COMPONENT: [
          { required: true, message: '请输入组件', trigger: 'blur' },
        ],
      },
    };
  },
  created() {
    this._recordForm = JSON.stringify(this.recordForm);
    this.query();
  },
  methods: {
    query() {
      this.tableParam.loading = true;
      this.$http
        .get('/api/permit/list', {
          params: {
            KEYWORD: this.tableParam.keyword,
            TYPE: this.tableParam.dropdown[this.tableParam.keycurrent].key,
            PROP: this.tableParam.prop,
            ORDER: this.tableParam.order,
            PAGESIZE: this.tableParam.pagesize,
            PAGENO: this.tableParam.pageno,
          },
        })
        .then(res => {
          this.tableParam.loading = false;
          if (res.data.flag === 'True') {
            this.tableParam.total = Number.parseInt(res.data.message, 10);
            this.records = res.data.result;
          }
        });
    },
    updateKeyCurrent(command) {
      this.tableParam.dropdown.forEach((item, index) => {
        if (item.key === command) {
          this.tableParam.keycurrent = index;
        }
      });
    },
    selectionChange(sels) {
      const list = [];
      sels.forEach(item => {
        list.push(this.records[item]);
      });
      this.selection = list;
    },
    recordFormInit() {
      if (this.$refs.recordForm) {
        this.$refs.recordForm.resetFields();
      }
      this.recordForm = JSON.parse(this._recordForm);
    },
    currentChange(currentPage) {
      if (this.tableParam.pageno !== currentPage) {
        this.tableParam.pageno = currentPage;
        this.query();
      }
    },
    sortChange(s) {
      if (s.sortOrder) {
        this.tableParam.prop = s.sortProp;
        this.tableParam.order = s.sortOrder.includes('desc')
          ? 'descending'
          : 'ascending';
        this.tableParam.pageno = 1;
        this.query();
      }
    },
    delRecord(scope) {
      this.$confirm(
        '除非确保安全，否则我们不建议您进行此操作，一切后果自行负责！',
        '权限删除警告',
        { type: 'warning' },
      )
        .then(() => {
          this.$http
            .post('/api/permit/delete', { IDS: scope.row.ZK_ID })
            .then(res => {
              if (res.data.flag === 'True') {
                this.records.splice(scope.index, 1);
                this.$notify({
                  title: '成功',
                  message: '已成功删除一条权限信息',
                  type: 'success',
                });
              }
            });
        })
        .catch(() => {});
    },
    batchDelete() {
      const ids = [];
      if (this.selection.length === 0) {
        this.$message.error('请先选中需要删除的选项');
        return;
      }
      this.selection.forEach(item => {
        ids.push(item.ZK_ID);
      });
      this.$confirm(
        '除非确保安全，否则我们不建议您进行此操作，一切后果自行负责！',
        '权限删除警告',
        { type: 'warning' },
      )
        .then(() => {
          this.$http
            .post('/api/permit/delete', { IDS: ids.join(',') })
            .then(res => {
              if (res.data.flag === 'True') {
                this.$notify({
                  title: '成功',
                  message: '已成功删除多条信息(一秒后将自动刷新页面)',
                  type: 'success',
                });
                setTimeout(() => {
                  window.location.reload();
                }, 500);
              }
            });
        })
        .catch(() => {});
    },
    getRecord(scope) {
      this.$http
        .get('/api/permit/detail', { params: { UID: scope.row.ZK_ID } })
        .then(res => {
          if (res.data.flag === 'True') {
            this.recordForm.record = res.data.result;
            this.recordForm.flag = false;
            this.recordForm.visible = true;
            this.recordForm.index = scope.index;
            this.recordForm.ishidden = res.data.result.ZK_ISHIDDEN === '1';
          }
        });
    },
    insertRecord() {
      this.$refs.recordForm.validate(valid => {
        if (valid) {
          this.recordForm.record.ZK_ISHIDDEN = this.recordForm.ishidden
            ? '1'
            : '0';
          this.$http
            .post('/api/permit/insert', this.recordForm.record)
            .then(res => {
              if (res.data.flag === 'True') {
                this.records.unshift(
                  JSON.parse(JSON.stringify(this.recordForm.record)),
                );
                this.$notify({
                  title: '成功',
                  message: '新增成功(一秒后将自动刷新页面)',
                  type: 'success',
                });
                this.recordFormInit();
                setTimeout(() => {
                  window.location.reload();
                }, 500);
              }
            });
        } else {
          this.$message.warning('请验证数据有效性');
        }
      });
    },
    updateRecord() {
      this.$refs.recordForm.validate(valid => {
        if (valid) {
          this.recordForm.record.ZK_ISHIDDEN = this.recordForm.ishidden
            ? '1'
            : '0';
          this.$http
            .post('/api/permit/update', this.recordForm.record)
            .then(res => {
              if (res.data.flag === 'True') {
                const form = JSON.parse(JSON.stringify(this.recordForm.record));
                this.records[this.recordForm.index].ZK_ICON = form.ZK_ICON;
                this.records[this.recordForm.index].ZK_PATH = form.ZK_PATH;
                this.records[this.recordForm.index].ZK_COMPONENT = form.ZK_COMPONENT;
                this.records[this.recordForm.index].ZK_NAME = form.ZK_NAME;
                this.records[this.recordForm.index].ZK_ISHIDDEN = form.ZK_ISHIDDEN;
                this.records[this.recordForm.index].ZK_ISLEAF = form.ZK_ISLEAF;
                this.records[this.recordForm.index].ZK_PARENT = form.ZK_PARENT;
                this.$notify({
                  title: '成功',
                  message: '更新权限成功',
                  type: 'success',
                });
                this.recordFormInit();
              }
            });
        } else {
          this.$message.warning('请验证数据有效性');
        }
      });
    },
  },
};
</script>

<style>
#Permit_vue .botton_toolbar {
  border: 1px solid #f2f2f2;
  box-shadow: 0 0 5px #f2f2f2;
  padding: 10px;
  margin: 10px 0 20px 0;
}
#Permit_vue .botton_toolbar:hover {
  background: #f2f2f2;
  box-shadow: none;
}
</style>
